package com.example.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 17:23
 **/
public class DataSourceUtils {
    private static DataSource dataSource = null;

    static {
        try (InputStream is = DataSourceUtils.class.getClassLoader()
                .getResourceAsStream("druid.properties");) {
            Properties prop = new Properties();

            prop.load(is);

            //
            dataSource = DruidDataSourceFactory.createDataSource(prop);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection getConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return con;
    }

    public static void close(Connection con, Statement stat) {
        close(con, stat, null);
    }

    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
